<?php

namespace addons\thirdwork\library;

use addons\thirdwork\model\Thirdwork;
use app\common\library\Auth;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\exception\PDOException;

/**
 * 第三方登录服务类
 *
 * @author Karson
 */
class Service
{

	/**
	 * 第三方登录
	 * @param string $platform 平台
	 * @param array $params 参数
	 * @param array $extend 会员扩展信息
	 * @param int $keeptime 有效时长
	 * @return boolean
	 */
	public static function connect($platform, $params = [], $extend = [], $keeptime = 0)
	{
		$time   = time();
		$values = [
			'platform'      => $platform,
			'openid'        => $params['openid'],
			'openuserid'    => $params['userinfo']['userid'],
			'openname'      => isset($params['userinfo']['nickname']) ? $params['userinfo']['nickname'] : '',
			'access_token'  => $params['access_token'],
			'refresh_token' => isset($params['refresh_token']) ? $params['refresh_token'] : '',
			'expires_in'    => $params['expires_in'],
			'logintime'     => $time,
			'expiretime'    => $time + $params['expires_in'],
		];

		$fields = [];
		if (isset($params['userinfo']['userid'])) {
			$fields['username'] = $params['userinfo']['userid'];
		}
		if (isset($params['userinfo']['email'])) {
			$fields['email'] = $params['userinfo']['email'];
		}
		if (isset($params['userinfo']['mobile'])) {
			$fields['mobile'] = $params['userinfo']['mobile'];
		}
		if (isset($params['userinfo']['avatar'])) {
			$fields['avatar'] = htmlspecialchars(strip_tags($params['userinfo']['avatar']));
		}

		$auth = Auth::instance();
		$auth->keeptime($keeptime);

		$thirdwork = Thirdwork::get(['platform' => $platform, 'openuserid' => $params['userinfo']['userid']]);
		if ($thirdwork) { //如果存在绑定关系就直接登录
			$user = User::get($thirdwork['user_id']);
			if (!$user) {
				return FALSE;
			}

			$thirdwork->save($values);
			$user->save($fields);

			return $auth->direct($user->id);
		} else {
			Db::startTrans();
			try {
				$user = User::get(['username' => $values['openuserid']]);
				if (empty($user)) { //如果用户未同步，先注册
					// 先随机一个用户名,随后再变更为u+数字id
					$username           = Random::alnum(20);
					$password           = '123456';
					$extend['group_id'] = 1;
					$domain             = request()->host();

					// 默认注册一个会员
					$result = $auth->register($username, $password, $username . '@' . $domain, '', $extend, $keeptime);
					if (!$result) {
						return FALSE;
					}
					$user = $auth->getUser();
					$user = User::get($user->id);
				}
				$user->save($fields);
				// 保存第三方信息
				$values['user_id'] = $user->id;
				Thirdwork::create($values);
				Db::commit();
			} catch (PDOException $e) {
				Db::rollback();
				$auth->logout();
				return FALSE;
			}

			// 写入登录Cookies和Token
			return $auth->direct($user->id);
		}
	}
}
